<template>
  <el-container>
    <el-main>
        <el-row class="table-wrapper">
          <el-col :span='24'>  
            <el-form :inline="true" label-width="80px"> 
              <el-form-item label="分站" v-if="role === 'SUPER_ADMIN'">
                <el-select v-model="namespace" placeholder="分站名称">
                  <el-option
                    v-for="site in allSites"
                    :key="site.namespace"
                    :label="site.namespaceDesc"
                    :value="site.namespace">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="用户名">
                <el-input placeholder="用户名" v-model="userName"  style="width: 200px;" clearable></el-input>
              </el-form-item>
              <el-form-item label="手机号码">
                  <el-input placeholder="手机号码" v-model="telNum"  style="width: 200px;" clearable></el-input>
              </el-form-item>
              
              <el-form-item>
                  <el-button type="primary" @click="getUserList()">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
            <!-- <el-col :span="6"> 
            <span>注册时间</span>
            <el-input placeholder="注册时间" v-model="gmtCreate"  style="width: 200px;" clearable>
            </el-input>
            </el-col>
            <el-col :span="6"> 
            <span>余额></span>
            <el-input placeholder="余额" v-model="outOrderId"  style="width: 200px;" clearable>
            </el-input>
            </el-col> -->
        </el-row>
      <div class="table_container">
        <div class="Pagination" style="text-align: left;margin-top: 10px;">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[20, 50, 80, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </div>
        <el-table
            :data="users"
            v-loading="tableLoading"
            highlight-current-row
            style="width: 100%">
            <!-- <el-table-column
              type="index"
              width="80">
            </el-table-column> -->
            <el-table-column
              property="id"
              label="用户ID"
              width="130">
            </el-table-column>
            <el-table-column
              property="userName"
              label="用户名"
              width="130">
            </el-table-column>
              <el-table-column
              label="用户等级"
              width="130">
              <template slot-scope="scope">
                <div v-if="scope.$index != editedRow">
                  {{scope.row.levelDesc}}
                </div>
                <div v-else>
                  <el-select v-model="editedLevel" placeholder="请选择用户等级">
                    <el-option
                      v-for="item in levels"
                      :key="item.id"
                      :label="item.levelDesc"
                      :value="item.id">
                      </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              property="telNum"
              label="联系电话"
              width="130">
            </el-table-column>
            <el-table-column
              property="gmtCreate"
              label="创建时间"
              width="180">
            </el-table-column>
            
            <el-table-column
              label="账户余额"
              width="130">
              <template slot-scope="scope">
                  {{ scope.row.balance/100}}
              </template>
            </el-table-column>
            <el-table-column
                label="状态"
                width="130">
                <template slot-scope="scope">
                  {{ scope.row.userStatus === 'ENABLE' ? '有效' : '无效'}}
                </template>
            </el-table-column>
            <el-table-column
                label="分站"
                prop="namespace"
                width="100">
            </el-table-column>
            <el-table-column
                label="操作"
                width="400">
                <template slot-scope="scope">
                  <el-button @click="showAccountDetail(scope.$index)" type="text" size="small" v-if="scope.$index != editedRow">账户明细</el-button>
                  <el-button size="small" type="text" @click="handleEdit(scope.$index)" v-if="scope.$index != editedRow">编辑</el-button>
                  <el-button size="small" type="text" @click="handleEditOk(scope.$index)" v-if="scope.$index == editedRow">确定</el-button>
                  <el-button size="small" type="text" @click="handleEditCancel(scope.$index)" v-if="scope.$index == editedRow">取消</el-button>  
                  <!-- <el-button type="primary" @click="showAccountDetail(scope.$index, 'deposit')">打款记录</el-button> -->
                  
                  <!-- <el-button type="primary" @click="showAccountDetail(scope.$index, 'consume')">消费记录</el-button> -->
                  
                  <!-- <el-button type="primary" @click="showAccountBalance(scope.$index)">查看余额</el-button> -->
                </template>
                
            </el-table-column>
        </el-table>
        <div class="Pagination" style="text-align: left;margin-top: 10px;">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[20, 50, 80, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </div>
      </div>
    </el-main>
    <el-dialog title="充值信息" :visible.sync="dialogTableVisible">
      <accountDetailList v-if='dialogTableVisible' :userName="user.userName" :balance="user.balance" :id="user.id" v-on:balance-update='balanceUpdate'>
      </accountDetailList>
    </el-dialog>
  </el-container>
</template>

<script>
  import {adminGetUserInfo, updateUserInfo} from '@/api/admin'
  import {getUserAccount} from '@/api/myinfo'
  import {getAllLevel} from '@/api/level'
  import accountDetailList from '@/page/admin/accountDetailList'
  import { mapState } from 'vuex'

  export default {
    data () {
      return {
        currentPage: 1,
        limit: 20,
        total: 0,
        users: [],
        allLevels: [],
        levels: [],
        tableLoading: false,
        userName: '',
        telNum: '',
        namespace: '',
        gmtCreate: '',
        editedRow: -1,
        editedLevel: 0,
        user: null,
        dialogTableVisible: false
      }
    },
    computed: {
      ...mapState('manage', ['allSites']),
      ...mapState(['role'])
    },
    components: {
      accountDetailList
    },
    created () {
      this.getUserList()
      this.refreshLevelList()
    },
    methods: {
      async refreshLevelList () {
        try {
          const result = await getAllLevel(true)
          if (result.status === 200 && result.data.code === 200) {
            this.allLevels = result.data.data
          } else {
            throw new Error('获取等级失败')
          }
        } catch (err) {
          // this.$message.error('列表获取失败')
          console.log('获取等级失败', err)
        }
      },
      async getUserList () {
        this.tableLoading = true
        try {
          const params = this.checkParam()
          // const result = await adminGetUserInfo({
          //   pageIndex: this.currentPage,
          //   pageSize: this.limit
          // })
          const result = await adminGetUserInfo(params)
  
          if (result.status === 200 && result.data.code === 200) {
            this.users = result.data.data
            this.total = result.data.page.total
          } else {
            throw new Error('获取数据失败')
          }
        } catch (err) {
        // this.$message.error('获取数据失败')
          console.log('获取数据失败', err)
        }
        this.tableLoading = false
      },
  
      async getUserBalance (user) {
        try {
          // const account = await getAccount();
          const result = await getUserAccount({userId: user.id})
          if (result.status === 200 && result.data.code === 200) {
            let data = result.data
            user.balance = data.data.balance
            // this.$alert(`用户 ${user.userName} 余额为：${data.data.balance / 100} 金币`, '', {
            //   confirmButtonText: '确定'
            // })
          }
        } catch (err) {
          console.log(err)
        }
      },
      handleEdit (row) {
        this.editedRow = row
        let user = this.users[row]
        this.editedLevel = user.levelDesc
        this.levels = this.allLevels.filter(e => e.namespace === user.namespace)
        // let priceRow = this.priceList[row]
        // this.price = priceRow.price / 100
        // this.status = priceRow.status
      },

      async handleEditOk (row) {
        try {
          const result = await updateUserInfo({
            id: this.users[row].id,
            levelId: this.editedLevel
          })
          if (result.status === 200 && result.data.code === 200) {
            // this.priceList[row].price = this.price * 100
            // this.priceList[row].status = this.status
            this.getUserList()
            this.editedRow = -1
          } else {
            throw new Error('获取数据失败')
          }
        } catch (err) {
          // this.$message.error('更新失败')
          console.log('获取数据失败', err)
        }
      },

      handleEditCancel (row) {
        this.editedRow = -1
      },
      showAccountBalance (user) {
        this.getUserBalance(user)
      },

      showAccountDetail (index) {
        this.user = this.users[index]
        this.dialogTableVisible = true
        // let link = this.$router.resolve({path: '/accountDetailList', query: { id: user.id, name: user.userName, balance: user.balance }})
        // window.open(link.href, '_blank')
      },
      balanceUpdate () {
        this.showAccountBalance(this.user)
      },
      handleSizeChange (size) {
        this.limit = size
        this.getUserList()
      },
      handleCurrentChange (page) {
        this.currentPage = page
        this.getUserList()
      },
      checkParam () {
        let params = {
          pageIndex: this.currentPage,
          pageSize: this.limit
          // status:"FINISH"
        }

        if (this.userName !== '') {
          params['userName'] = this.userName
        }

        if (this.namespace !== '') {
          params['namespace'] = this.namespace
        }

        if (this.telNum !== '') {
          params['telNum'] = this.telNum
        }
        // if (this.gmtCreate !== '') {
        //   params['gmtCreate'] = this.gmtCreate
        // }
        return params
      }

    }
  
  }
</script>

<style lang="less" scoped>
  .table-wrapper {
      border: 1px solid #ebeef5;
      margin: 30px 0;
      padding-top: 20px;
      padding-left: 10px;
  }
</style>